<!--经销商设置-->
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button  icon="el-icon-plus" v-waves :loading="downloadLoading" class="filter-item right-btn" type="primary" @click="toAdd">
        添加
      </el-button>
    </div>
    <ve-table
      :columns="columns"
      :table-data="tableData"
      row-key-field-name="id"
      :border-x="true"
      :border-y="true"
      :row-style-option="rowStyleOption"
      :checkbox-option="checkboxOptipon"/>
    <div class="table-pagination">
      <ve-pagination
        :total="totalCount"
        :page-index="pageIndex"
        :page-size="pageSize"
        @on-page-number-change="pageNumberChange"
        @on-page-size-change="pageSizeChange"/>
    </div>
    <el-dialog class="lnk-dialog"
               :close-on-click-modal="false"
               :title="dialogTitle"
               top="10vh"
               width="30%"
               :visible.sync="newDialog"
               :append-to-body="true">
      <el-form ref="mainForm" :model="formData" :rules="rules"
               size="mini" class="editForm">
        <!--表单项-->
        <el-row>
          <el-col>
            <el-form-item label="经销商" prop="name" class="car-form-item">
              <el-input class="car-modal-col" v-model="formData.name" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="newDialog = false;$refs['mainForm'].resetFields();">取消</el-button>
        <el-button type="primary" @click="addData()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
  .table-pagination {
    margin-top: 20px;
    text-align: right;
  }

  .right-btn {
    float: right;
  }

  .dialog-footer {
    text-align: center;
  }

  .car-modal-col {
    width: 280px;
  }
</style>

<script>

  export default {
    data() {
      return {
        rules: {
          name: [{required: true, message: '必输', trigger: 'blur'}],
        }, // 表单校验规则
        tableData: [],
        totalCount: '',
        dialogTitle: '新增经销商', // 弹框名称
        editorFlag: false,
        newDialog: false, // 添加弹框
        formData: {}, // 添加表单
        appId:"",
        pageIndex: 1,
        pageSize: 10,
        listQuery: {},
        rowStyleOption: { // 表格样式
          stripe: true, // 斑马纹
          hoverHighlight: true, // hover高亮
          clickHighlight: true // 点击行高亮
        },
        checkboxOptipon: {
          // 行选择改变事件
          selectedRowChange: ({row, isSelected, selectedRowKeys}) => {
            console.log(row, isSelected, selectedRowKeys)
          },
          // 全选改变事件
          selectedAllChange: ({isSelected, selectedRowKeys}) => {
            console.log(isSelected, selectedRowKeys)
          }
        },
        columns: [
          {
            field: '',
            key: 'f',
            // type=checkbox
            type: 'checkbox',
            title: '',
            width: 50,
            align: 'center'
          },
          {
            field: 'name',
            key: 'a',
            title: '经销商',
            align: 'center'
          },
          {field: 'createTime', key: 'b', title: '创建时间', align: 'center'},
          {
            field: 'status', key: 'e', title: '状态',
            renderBodyCell: ({row, column, rowIndex}, h) => {
              // 在这里写转换方法
              return (
              <span>
              {row.status === 1?<el-tag type={'success'}>启用</el-tag>:<el-tag type={'danger'}>禁用</el-tag>}
            </span>
            )
            }
          },
          {
            field: 'hobby', key: 'k', title: '操作',
            align: 'center',
            renderBodyCell: ({ row, column, rowIndex }, h) => {
              return (
              <span>
                <el-button circle icon="el-icon-edit" class='filter-item' type={'primary'} on-click={()=>this.editorDealer(row)}></el-button>
                {row.status === 1?<el-button circle icon="el-icon-remove" class='filter-item' type={'info'} on-click={()=>this.forbidorDealer(row)}></el-button>
                :<el-button circle icon="el-icon-success" class='filter-item' type={'success'} on-click={()=>this.forbidorDealer(row)}></el-button>
                }
                <el-button circle icon="el-icon-delete" class='filter-item' type={'danger'} on-click={()=>this.deleteorDealer(row)}></el-button>
              </span>
              )
            }
          }
        ]
      }
    },
    computed: {
    },
    created() {
      this.appId = sessionStorage.getItem("appId");
      this.initDatabase();
    },
    methods: {
      // page number change
      pageNumberChange(pageIndex) {
        this.pageIndex = pageIndex
        this.initDatabase();
      },

      // page size change
      pageSizeChange(pageSize) {
        this.pageIndex = 1;
        this.pageSize = pageSize;
        this.initDatabase();
      },

      /**
       * 初始化数据
       * @date 2021-05-10
       */
      async initDatabase() {
        this.tableData = [];
        let param = {appId: await sessionStorage.getItem("appId")};
        let data = await this.$http.post('/auth/distributor/list/'+this.pageIndex+"/"+this.pageSize, param);
        console.log(data);
        if (data.code === 200) {
          this.tableData = data.data;
          this.totalCount = data.total;
        } else {
          this.$message({
            type: 'error',
            message: '查询失败，请刷新页面'
          });
        }
        console.log(this.tableData)
      },
      /**
       * 禁用
       * @param {Object} row
       */
      async forbidorDealer(row) {
        let that = this
        this.$alert('是否确认禁用', '确认禁用', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            that.formData = row;
            if (row.status === 1) {
              that.formData.status = 0;
            } else {
              that.formData.status = 1;
            }
            let data = await that.$http.post('/auth/distributor/update', that.formData)
            console.log(data);
            if (data.code === 200) {
              that.initDatabase();
            } else {
              that.$message({
                type: 'error',
                message: '操作失败'
              });
            }
          }).catch(() => {
          that.$message({
            type: 'info',
            message: '已取消'
          });
        });
      },

      /**
       * 删除
       * @param {Object} row
       */
      async deleteorDealer(row) {

        let that = this

        this.$alert('是否确认删除', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = await that.$http.delete('/auth/distributor/delete/' + row.id, {})
          console.log(data);
          if (data.code === 200) {
            that.initDatabase();
          } else {
            that.$message({
              type: 'info',
              message: '操作失败，请重试'
            });
          }
        })
      },

      /**
       * 编辑
       * @date 2021-05-08
       * @param row
       */
      editorDealer(row) {
        this.formData = row
        this.newDialog = true
        this.editorFlag = true // 编辑标识
        this.dialogTitle = '编辑经销商'
      },
      /**
       * 点击新增按钮
       * @date 2021-05-08
       */
      toAdd() {
        this.formData = {}
        this.newDialog = true
        this.editorFlag = false  // 编辑标志
        this.dialogTitle = '新增经销商'
      },
      /**
       * 编辑操作
       * @date 2021-05-17
       */
      editorData () {

      },
      /**
       * 新增操作
       * @date 2021-05-08
       */
      async addData() {
        this.$refs['mainForm'].validate(async (valid) => {
          if (valid) {
            if (this.formData.id) {
              let data = await this.$http.post('/auth/distributor/update', this.formData)
              console.log(data);
              if (data.code === 200) {
                this.newDialog = false;
                this.initDatabase();
              } else {
                this.$message({
                  type: 'info',
                  message: '操作失败，请重试'
                });
              }
            } else {
              this.formData.appId = this.appId;
              let data = await this.$http.post('/auth/distributor/save', this.formData)
              if (data.code === 200) {
                this.newDialog = false;
                this.initDatabase();
              } else {
                this.$message({
                  type: 'info',
                  message: '操作失败，请重试'
                });
              }
            }
          }
        })
      }
    }
  }
</script>
